package com.leetcode.dynamic_programming;

/**
 * @author Dennis Li
 * @date 2020/9/9 16:45
 */
public class MaximalSquare_221 {

    public int maximalSquare(char[][] matrix) {
        int m = matrix.length, n = matrix[0].length;
        int[][] dp = new int[m][n];
        int max = 0;

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (matrix[i][j] == '1') {
                    if (i == 0 || j == 0) {
                        dp[i][j] = 1;
                    } else {
                        // 选左方、左上和上方的最小值加一，可以确定矩阵
                        dp[i][j] = 1 + Math.min(dp[i - 1][j], Math.min(dp[i - 1][j - 1], dp[i][j - 1]));
                    }
                    max = Math.max(dp[i][j], max);
                }
            }
        }

        return max * max;
    }

}
